#include "../include/Acceptor.h"
#include "../include/Logger.h"

namespace myNameSpace {
Acceptor::Acceptor(unsigned short port, const string &ip): _listenSock(), _addr(port, ip) {}

void Acceptor::ready() {
    setAddrReuse(true);
    setPortReuse(true);
    bind();
    listen();
}

int Acceptor::accept() {
    int netFd = ::accept(getFd(), nullptr, nullptr); // 使用命名空间解决Acceptor::bind和Linux网络编程中的bind，C语言中的函数默认放在匿名命名空间中
    if (netFd == -1) {
        perror("accept");
    }
    return netFd;
}

int Acceptor::getFd() const {
    return _listenSock.getFd();
}

void Acceptor::setAddrReuse(bool isReuse) {
    int reuse = isReuse;
    int ret = setsockopt(getFd(), SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
    if (ret == -1) {
        perror("setsockopt");
    }
}

void Acceptor::setPortReuse(bool isReuse) {
    int reuse = isReuse;
    int ret = setsockopt(getFd(), SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(reuse));
    if (ret == -1) {
        perror("setsockopt");
    }
}

void Acceptor::bind() {
    int ret = ::bind(getFd(), (struct sockaddr *)_addr.getInetAddrPtr(), sizeof(_addr));
    if (ret == -1) {
        perror("bind");
    }
}

void Acceptor::listen() {
    int ret = ::listen(getFd(), 20000);
    if (ret == -1) {
        perror("listen");
    }
    moqi::LOG_INFO("Thread %u: Listening...", pthread_self());
}
} // end of namespace myNameSpace
